package com.sczmgk.hotline_pzh.mainhomeUiView;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Message;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.hyphenate.chat.EMClient;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.sczmgk.hotline_pzh.MyApp;
import com.sczmgk.hotline_pzh.R;
import com.sczmgk.hotline_pzh.base.MainHomeBaseView;
import com.sczmgk.hotline_pzh.constants.Constants;
import com.sczmgk.hotline_pzh.db.impl.UserDaoImpl;
import com.sczmgk.hotline_pzh.dialog.DialogFactory;
import com.sczmgk.hotline_pzh.dialog.MessageDialog;
import com.sczmgk.hotline_pzh.entity.MessageCountBean;
import com.sczmgk.hotline_pzh.entity.User;
import com.sczmgk.hotline_pzh.httputils.MyHttp;
import com.sczmgk.hotline_pzh.jpush.MainHomeDataObserver;
import com.sczmgk.hotline_pzh.sp.CacheUtils;
import com.sczmgk.hotline_pzh.ui.AboutUsActivity;
import com.sczmgk.hotline_pzh.ui.ChangePasswordActivity;
import com.sczmgk.hotline_pzh.ui.LoginActivity;
import com.sczmgk.hotline_pzh.ui.MyCollectionActivity;
import com.sczmgk.hotline_pzh.ui.MyMessageActivity;
import com.sczmgk.hotline_pzh.ui.MyWorkActivity;
import com.sczmgk.hotline_pzh.ui.PersonalInfoActivity;
import com.sczmgk.hotline_pzh.utils.FileUtil;
import com.sczmgk.hotline_pzh.utils.MyLog;
import com.sczmgk.hotline_pzh.utils.UIUtils;
import com.sczmgk.hotline_pzh.view.HeadPortraitView;
import com.sczmgk.hotline_pzh.view.PersonalItemView;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Observable;
import static com.sczmgk.hotline_pzh.ui.MainActivity.REQUEST_CODE_LOGIN;

/**
 * Created by Administrator on 2016/11/21 0021.
 */
public class MainHomeMe extends MainHomeBaseView implements View.OnClickListener {

    /**
     * 普通用户的类型
     */
    private static final int NORMAL_USER = 0;

    /**
     * 网格化管理员的类型
     */
    private static final int MANAGE_USER = 1;

    //主界面和投诉的RadioButton
    private RadioButton mHomeRb;
    private RadioButton mComplaint;

    //个人信息设置的控件
    private LinearLayout mPersonalSetting;
    //个人信息头像
    private HeadPortraitView mIvPhoto;
    //个人信息姓名
    private TextView mTvName;

    //我的消息
    private PersonalItemView mMyMsg;
    //我的投诉
    private PersonalItemView mMyComplaint;
    //我的收藏
    private PersonalItemView mMyCollection;
    //我的工作
    private PersonalItemView mMyWork;
    //关于我们
    private PersonalItemView mAboutUs;
    //修改密码
    private PersonalItemView mChangePwd;
    //退出登录
    private PersonalItemView mLoginout;

    private MyApp myApp;

    //弹出dialog
    MessageDialog messageDialog = DialogFactory.chooseDialog(activity, activity.getResources().getString(R.string.dialog_login_show),
            activity.getResources().getString(R.string.sure), activity.getResources().getString(R.string.cancel), new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(activity, LoginActivity.class);
                    activity.startActivityForResult(intent, REQUEST_CODE_LOGIN);
                }
            }, new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                }
            });
    private MessageDialog dialog;

    public MainHomeMe(Activity context, RadioButton mHomeRb, RadioButton mComplaint) {
        super(context);
        this.mHomeRb = mHomeRb;
        this.mComplaint = mComplaint;

        initView();

        initData();

        setListener();



    }

    @Override
    public void mHandleMessage(Message msg) {
        switch (msg.what) {
            case Constants.MY_WORK_HANDLE_FLAG:
                //点击我的工作条目时的回调
                mComplaint.setChecked(true);
                break;
        }
    }

    /**
     * 初始化控件
     */
    @Override
    public void initView() {

        View meView = View.inflate(activity, R.layout.me_layout, null);

        //个人中心信息设置
        mPersonalSetting = (LinearLayout) meView.findViewById(R.id.ll_me_personal);

        //我的消息
        mMyMsg = (PersonalItemView) meView.findViewById(R.id.piv_my_msg);
        //我的投诉
        mMyComplaint = (PersonalItemView) meView.findViewById(R.id.piv_my_complaint);
        //我的收藏
        mMyCollection = (PersonalItemView) meView.findViewById(R.id.piv_my_collection);
        //我的工作
        mMyWork = (PersonalItemView) meView.findViewById(R.id.piv_my_work);
        //关于我们
        mAboutUs = (PersonalItemView) meView.findViewById(R.id.piv_about_us);
        //修改密码
        mChangePwd = (PersonalItemView) meView.findViewById(R.id.piv_change_pwd);
        //退出登录
        mLoginout = (PersonalItemView) meView.findViewById(R.id.piv_login_out);

        //头像
        mIvPhoto = (HeadPortraitView) meView.findViewById(R.id.head_photo_me);
        //姓名
        mTvName = (TextView) meView.findViewById(R.id.tv_me_name);

        myApp = (MyApp) activity.getApplication();

        container.addView(meView);
    }

    /**
     * 初始化数据
     */
    private void initData() {

    }

    /**
     * 设置监听器
     */
    private void setListener() {

        //设置个人信息的点击事件
        mPersonalSetting.setOnClickListener(this);

        //我的消息的点击事件
        mMyMsg.setOnClickListener(this);
        //我的投诉的点击事件
        mMyComplaint.setOnClickListener(this);
        //我的收藏的点击事件
        mMyCollection.setOnClickListener(this);
        //我的工作的点击事件
        mMyWork.setOnClickListener(this);
        //修改密码的点击事件
        mChangePwd.setOnClickListener(this);
        //退出登录的点击事件
        mLoginout.setOnClickListener(this);

        //关于我们的点击事件
        mAboutUs.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //关于我们
                UIUtils.startActivity(activity, AboutUsActivity.class);
            }
        });

    }

    @Override
    public void onClick(View view) {

        //判断是否登录
        boolean isLogin = CacheUtils.getBooleanData(activity, Constants.IS_LOGIN_KEY, false);
        if (!isLogin) {
            if (messageDialog != null && !messageDialog.isShowing()) {
                messageDialog.show();
            }
            return;
        }

        switch (view.getId()) {

            case R.id.ll_me_personal:

                //个人信息
                UIUtils.startActivity(activity, PersonalInfoActivity.class);
                break;

            case R.id.piv_my_msg:

                //我的消息
                Intent intent = new Intent(activity, MyMessageActivity.class);
                activity.startActivity(intent);
                break;

            case R.id.piv_my_complaint:

                //我的投诉
                mComplaint.setChecked(true);
                break;

            case R.id.piv_my_collection:

                //我的收藏
                UIUtils.startActivity(activity, MyCollectionActivity.class);
                break;

            case R.id.piv_my_work:

                //我的工作
                intent = new Intent(activity, MyWorkActivity.class);
                activity.startActivity(intent);
                break;

            case R.id.piv_change_pwd:

                //修改密码
                intent = new Intent(activity, ChangePasswordActivity.class) ;
                activity.startActivityForResult(intent ,Constants.REQUEST_CODE_CHANGE_PWD);
                break;

            case R.id.piv_login_out:

                //退出登录
                //展示退出的dialog
                showDialog();
                break;

        }
    }

    /**
     * 展示退出登录的dialog
     */
    private void showDialog() {


        if (dialog == null || !dialog.isShowing()) {
            dialog = DialogFactory.chooseDialog(activity, activity.getResources().getString(R.string.logo_out), activity.getResources().getString(R.string.sure), new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    CacheUtils.cacheBooleanData(activity, Constants.IS_LOGIN_KEY, false);
                    CacheUtils.cacheIntData(activity, Constants.LOGIN_UID, 0);
                    EMClient.getInstance().logout(true);
                    mHomeRb.setChecked(true);
                    MainHomeDataObserver.getInstance().hasNewMes(true);
//                mHandler.sendEmptyMessage(Constants.LOGIN_OUT_CHANGE_DATA) ;
                }
            });
        }
    }

    /**
     * 设置红点的显示与数字
     * @param number 红点显示的数字
     * @param piv    控件
     */
    public void setPointText(String number, PersonalItemView piv) {
        if (Integer.parseInt(number) > 0) {
            piv.setInformationNum(number, true);
        } else {
            piv.setInformationNum("", false);
        }
    }

    /**
     * 设置红点的显示与数字
     * @param number 红点显示的数字
     * @param piv    控件
     */
    public void setPointText(int number, PersonalItemView piv) {
        if (number > 0) {
            piv.setInformationNum(String.valueOf(number), true);
        } else {
            piv.setInformationNum("", false);
        }
    }

    @Override
    public void update(Observable observable, Object o) {
        super.update(observable, o);

        if (CacheUtils.getBooleanData(activity , Constants.IS_LOGIN_KEY , false)){
            //设置消息红点
            MessageCountBean count = (MessageCountBean) o;
            setPointText(count.msgcount, mMyMsg);
            setPointText(count.taskcount, mMyWork);
        }

    }

    @Override
    public void onResume() {
        super.onResume();
       refreshUserInfo();

    }

    private void refreshUserInfo() {


        boolean isLogin = CacheUtils.getBooleanData(activity, Constants.IS_LOGIN_KEY, false);
        if (isLogin) {
            //显示改变密码和登录登出
            mChangePwd.setVisibility(View.VISIBLE);
            mLoginout.setVisibility(View.VISIBLE);
            int userid = CacheUtils.getIntData(activity, Constants.LOGIN_UID, 0);
            final User user = UserDaoImpl.getIntance(activity).findByQuery(userid);

            if (user != null) {
                //设置头像
                Bitmap bitmap = com.sczmgk.hotline_pzh.utils.BitmapUtils.getBitmap(user.imageLocalPath, 200, 200);
                if (bitmap != null) {
                    mIvPhoto.getImageView().setImageBitmap(bitmap);
                } else {
                    MyLog.d(TAG, "没取到头像的图片--去下载--： url: " + Constants.BASE_URL + Constants.GET_DOWNLOAD_FILE_URL + user.headurl);
                    mIvPhoto.getImageView().setImageResource(R.drawable.chat_default_user_header);
                    final String localPath = FileUtil.getUserCaptureCacheFilePath(user.userid+"");
                    Map<String, Object> downLoadMaps = new HashMap<String, Object>();
                    downLoadMaps.put("filename", user.imageLocalPath);
                    MyHttp.downloadFile(Constants.BASE_URL + Constants.GET_DOWNLOAD_FILE_URL + user.headurl,
                            localPath, new RequestCallBack<File>() {

                                @Override
                                public void onSuccess(ResponseInfo<File> responseInfo) {
                                    MyLog.d(TAG, " 下载图片成功了 ！ ");

                                    user.imageLocalPath = localPath;

                                    UserDaoImpl.getIntance(activity).updata(user);

                                    refreshUserInfo();
                                }

                                @Override
                                public void onFailure(HttpException error, String msg) {

                                }

                                @Override
                                public void onException() {

                                }
                            });

                }
                //设置姓名
                mTvName.setText(user.consumersname);
                //判断是否是否是网格化管理员
                if (user.consumerstype == NORMAL_USER) {
                    //如果是用户
                    mMyWork.setVisibility(View.GONE);
                } else if (user.consumerstype == MANAGE_USER) {
                    //如果是网格化管理员
                    mMyWork.setVisibility(View.VISIBLE);
                }
            }
        } else {
            //没有登录 , 隐藏修改密码,退出登录,我的工作
            mChangePwd.setVisibility(View.GONE);
            mLoginout.setVisibility(View.GONE);
            mMyWork.setVisibility(View.GONE);
            //设置姓名
            mTvName.setText("");
            mIvPhoto.getImageView().setImageResource(R.drawable.chat_default_user_header);
        }
    }
}
